package com.tanhua.server.util;

import com.tanhua.domain.db.User;
import io.jsonwebtoken.*;

public class JwtUtils {
    /**
     * 生成token
     */
    public static String createToken(User user, String signature) {
        return Jwts.builder()
                .claim("id", user.getId())
                .claim("mobile", user.getMobile())
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
    }

    /**
     * 验证token是否合法
     */
    public static boolean isValidToken(String token, String signature) {
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 解析token
     */
    public static User parseToken(String token, String signature) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
        User user = new User();
        Object id = claimsJws.getBody().get("id");
        String mobile = (String) claimsJws.getBody().get("mobile");

        user.setId(Long.parseLong(id.toString()));
        user.setMobile(mobile);
        return user;
    }
}
